﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Collections;

namespace CarbonExchange.Bll
{
    public class AmeeDataCatagory
    {
        internal AmeeDataCatagory(XElement item, string path)
        {
            Path = path;
            Name = item.Element("DataCategory").Element("Name").Value;
            ChoiceName = item.Element("Choices").Element("Name").Value;
            if (ChoiceName.Equals("uid", StringComparison.InvariantCultureIgnoreCase))
            {
                Id = item.Element("Choices").Element("Choices").Element("Choice").Element("Value").Value;
                Choices = new List<string>();
            }
            else
            {
                Choices = (from choice in item.Element("Choices").Element("Choices").Elements("Choice") 
                           where !string.IsNullOrEmpty(choice.Element("Value").Value) 
                           select choice.Element("Value").Value).ToList();
            }
            _Selected = from choice in item.Element("Selections").Elements("Choice") 
                        select new SelectedItem(choice.Element("Name").Value, choice.Element("Value").Value);
        }

        public string Path { get; private set; }
        public string Id { get; private set; }
        public string Name { get; private set; }
        public List<string> Choices { get; private set; }
        public string ChoiceName { get; private set; }
        public bool HasChoices { get { return Choices.Count() > 0; } }
        public bool DataItemSelected { get { return !string.IsNullOrEmpty(Id); } }
        private IEnumerable<SelectedItem> _Selected;
        public SelectedItem[] Selected { get { return _Selected.ToArray(); } }


        public string SelectedAsString()
        {
            return _Selected.ToFormatedStringWithSpacer("&", "{0}={1}", x => x.Name, x => x.Value);
        }
    }

    public class SelectedItem
    {
        internal SelectedItem(string name, object value)
        {
            this.Name = name;
            this.Value = value;
        }

        public string Name { get; private set; }
        public object Value { get; private set; }
    }
}
